import {
	msg,
	connect
} from "./api.js";

//h5 检测登录
import $store from "./store/index.js";

export const config = {
	baseURL: '',
	// upURL:'/sys/common/upload',
	upURL: "/wechat/cp/api/base/upload",
	QNY: '',
	headers: {},
	errorCode: null,
	baseData: {},
	getBaseData: {},
	postBaseData: {}
}

//错误码拦截
const errorCode = res => {
	//登录过期处理
	if ([500].includes(res.status) && ~res.message.indexOf("登录")) {
		$store.dispatch('logout', true).then(r => {
			$store.dispatch('login');
		});
		return new Promise((r, reject) => {
			reject({
				...res,
				success: true
			});
		});
	}
	if (res.success + "" === "true") {
		return {
			...res,
			code: 200
		};
	}
	uni.showModal({
		title: "错误",
		content: res.message || '网络不通',
		showCancel: !1
	});
	return new Promise((r, reject) => {
		reject({
			...res,
			success: true
		});
	});
}
//请求
export const http = (url, data = {}, method) => {
	return uni.request({
		method,
		header: config.headers,
		url: connect(config.baseURL, url),
		data: {
			...config.baseData,
			...data
		}
	}).then(res => res[1] || {}).then(res => res.data || {}).then(typeof config.errorCode === 'function' ? config.errorCode :
		errorCode);
}
//get请求
export const httpGet = (url, data = {}) => {
	return http(url, {
		...data,
		...config.getBaseData
	}, "GET");
}
//post请求
export const httpPost = (url, data = {}) => {
	return http(url, {
		...data,
		...config.postBaseData
	}, "POST");
}
//put
export const httpPut = (url, data = {}) => {
	return http(url, data, "PUT");
}
//put
export const httpDelete = (url, data = {}) => {
	return http(url, data, "DELETE");
}
//上传
export const httpUp = (upURL, filePath, formData = {}, onProgressUpdate = e => {}, uploadTask = e => {}) => {
	const {...header} = config.headers;
	delete header['Content-Type'];
	delete header['ContentType'];
	return new Promise(r => {
		let Task = uni.uploadFile({
			url: connect(config.baseURL, upURL || config.upURL),
			filePath,
			name: 'avatar',
			formData,
			header,
			success: res => {
				try {
					res = JSON.parse(res.data);
					r({
						...res,
						message: '',
						path: res.message
					});
				} catch (e) {
					r({
						...res,
						message: '上传出错！',
						path: ''
					});
				}
			},
			fail: error => {
				r({
					message: '上传出错！',
					path: ''
				});
			}
		});
		Task.onProgressUpdate(function(res) {
			onProgressUpdate(res);
		});
		uploadTask(Task);
	}).then(res => {
		if (res.success + "" === "true") {
			return {
				...res,
				code: 200
			};
		}
		uni.showToast({
			title: '上传失败',
			duration: 2000,
			icon: "none"
		});
		return {
			path: ''
		}
	});
}
